<template>
  <a-spin :spinning="confirmLoading">
    <a-form
      :form="form"
      style="height: 525px"
    >
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="停车场编码"
        v-show="false"
      >
        <p
          placeholder="请输入停车场编码"
          v-decorator="['parkCode', {initialValue:this.parkCode}]"
        />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="停车场名称"
        v-show="false"
      >
        <p
          placeholder="请输入停车场名称"
          v-decorator="['parkName', {initialValue:this.parkName}]"
        />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="设备序列号，设备唯一"
        v-show="false"
      >
        <p
          placeholder="请输入设备序列号，设备唯一"
          v-decorator="['serialNo', {initialValue:this.ArmRadioSelected}]"
        />
      </a-form-item>
      <a-row
        :gutter="[8,8]"
        style="height: 90%;margin: 0px"
      >
        <a-col
          :span="3"
          style="height: 100%"
        >
          <div
            style="width: 100%;height: 100%"
            class="ThroughConfigDiv"
          >
            <a-row class="ThroughConfigDiv_Title">
              <p style="width: 33%;margin: auto;font-size: 13px;font-weight: 400;text-align: right">选择</p>
              <p style="width: 66%; margin: auto;font-size: 13px;font-weight: 400;text-align: center">车道</p>
            </a-row>
            <a-row class="ThroughConfigDiv_item">
              <div
                style="background-color: white"
                type="radio-box"
                v-for="item in ArmOptions"
                :key="item.id"
              >
                <span
                  class="radio"
                  :class="{'on' : item.isChecked}"
                ></span>
                <a-row style="margin-top: 5px">
                  <a-col
                    :span="8"
                    align="center"
                    style="height: 30px"
                  >
                    <input
                      style="margin-top: 10px;margin-bottom: 4px"
                      :value="item.value"
                      class="input-radio"
                      @click="ArmRadioChange(item.index)"
                      :checked="item.isChecked"
                      type="radio"
                    />
                  </a-col>
                  <a-col
                    :span="16"
                    align="center"
                    style="height: 30px "
                  >
                    <span class="RadioLabel">
                      {{ item.label }}
                    </span>
                  </a-col>
                </a-row>
              </div>
            </a-row>
          </div>
        </a-col>
        <a-col
          :span="4"
          style="height: 100%"
        >
          <a-form-item
            label="车辆禁行日"
            v-show="false"
          >
            <p v-decorator="['stopWeeklyDay', {initialValue:this.stopWeeklyDays}]"></p>
          </a-form-item>
          <a-row style="height: 36%">
            <a-col
              :span="24"
              style="height: 100%"
            >
              <div
                style="width: 100%;height: 100%"
                class="ThroughConfigDiv"
              >
                <a-row class="ThroughConfigDiv_Title">
                  <p style="margin: auto;font-size: 13px;font-weight: 400;text-align: center">禁止通行日选择</p>
                </a-row>
                <a-row class="ThroughConfigDiv_item">
                  <div
                    style="background-color: white"
                    type="radio-box"
                    v-for="item in DayOptions"
                    :key="item.id"
                  >
                    <span
                      class="radio"
                      :class="{'on' : item.isChecked}"
                    ></span>
                    <a-col :span="12">
                      <a-row>
                        <a-col
                          :span="7"
                          align="right"
                          style="height: 25px;margin-top: 7px"
                        >
                          <input
                            style="text-align: right"
                            :value="item.value"
                            class="input-radio"
                            @click="DayRadioChange(item.index)"
                            :checked="item.isChecked"
                            type="checkbox"
                          />
                        </a-col>
                        <a-col
                          :span="17"
                          align="center"
                          style="text-align: center;height: 25px;margin-top: 5px "
                        >
                          <p style="font-size: 13px ;margin-left: 5px;text-align: left">
                            {{ item.label }}</p>
                        </a-col>
                      </a-row>
                    </a-col>
                  </div>
                </a-row>
              </div>
            </a-col>
          </a-row>
          <a-row style="height: 3%"></a-row>
          <a-form-item
            label="控制车辆类型"
            v-show="false"
          >
            <p v-decorator="['carTypeId', {initialValue:this.carTypeIds}]"></p>
          </a-form-item>
          <a-row style="height: 36%">
            <a-col
              :span="24"
              style="height: 100%"
            >
              <div
                style="width: 100%;height: 100%"
                class="ThroughConfigDiv"
              >
                <a-row class="ThroughConfigDiv_Title">
                  <p style="margin: auto;font-size: 13px;font-weight: 400;text-align: center">受控车辆类型</p>
                </a-row>
                <a-row class="ThroughConfigDiv_item">
                  <div
                    style="background-color: white"
                    type="radio-box"
                    v-for="item in CarOptions"
                    :key="item.value"
                  >
                    <span
                      class="radio"
                      :class="{'on' : item.isChecked}"
                    ></span>
                    <a-row>
                      <a-col
                        :span="7"
                        align="right"
                        style="height: 20px;margin-top: 10px"
                      >
                        <input
                          style="text-align: right"
                          :value="item.value"
                          class="input-radio"
                          @click="CarRadioChange(item.index)"
                          :checked="item.isChecked"
                          type="checkbox"
                        />
                      </a-col>
                      <a-col
                        :span="17"
                        align="center"
                        style="height: 20px;margin-top: 8px "
                      >
                        <p style="width:80px;margin-left: 12px;white-space: nowrap;overflow:hidden;text-overflow:ellipsis;font-weight: 500;text-align: left">
                          {{ item.label }}</p>
                      </a-col>
                    </a-row>
                  </div>
                </a-row>
              </div>
            </a-col>
          </a-row>
          <a-row style="height: 25%">
            <a-col
              :span="24"
              style="height: 100%"
            >
              <a-row style="height: 40%;display: flex">
                <p style="margin: auto;margin-left: 0px;font-size: 15px;font-weight: 600">禁止通行时间段：</p>
              </a-row>
              <a-row style="height: 30%;display: flex">
                <a-form-item style="width: 100%">
                  <P
                    v-show="false"
                    v-decorator="['stopStartTime', {initialValue:'00:00:00'}]"
                  />
                  <a-time-picker
                    :value="this.stopStartTime"
                    :default-value="moment('00:00:00', 'HH:mm:ss')"
                    placeholder="开始时间"
                    :allow-clear="false"
                    @change="onStartTimeChange"
                  />
                </a-form-item>
              </a-row>
              <a-row style="height: 30%;display: flex">
                <a-form-item style="width: 100%">
                  <P
                    v-show="false"
                    v-decorator="['stopEndTime', {initialValue:'23:59:59'}]"
                  />
                  <a-time-picker
                    :value="this.stopEndTime"
                    :default-value="moment('23:59:59', 'HH:mm:ss')"
                    placeholder="结束时间"
                    :allow-clear="false"
                    @change="onEndTimeChange"
                  />
                </a-form-item>
              </a-row>
            </a-col>
          </a-row>

        </a-col>
        <a-col
          :span="1"
          style="height: 100%;"
        >
          <a-button
            icon="arrow-right"
            style=" margin: 200px 0px;height: 150px;width: 100%"
            @click="handleOk(false)"
          ></a-button>
        </a-col>
        <a-col
          :span="15"
          style="height: 100%;"
        >
          <a-spin :spinning="confirmLoading">
            <a-table
              style="height: 100%;border-style: solid;border-width: 2px;border-bottom-width: 2px;border-radius: 5px;border-color: #f1f3f4;font-size: 30px;"
              rowKey="id"
              :columns="TableColumns"
              :data-source="ThroughData"
              :scroll="{y:483}"
              :pagination="false"
            >
              <span
                slot="operation"
                slot-scope="text, record"
              >
                <a @click="Delete(record.id)">删除</a>
              </span>
            </a-table>
          </a-spin>
        </a-col>
      </a-row>
      <a-row style="height: 10%;">
        <a-col align="center">
          <a-button
            style="margin-right: 30px"
            @click="$emit('currentChange',2)"
          >上一步</a-button>
          <!-- <a-button style="margin-right: 30px" @click="FormReset()">重置设置</a-button> -->
          <a-button
            type="primary"
            @click="handleOk(true)"
          >确认设置</a-button>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script>
import { deleteAction, getAction, httpAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'ConfigParkThroughModal',
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      ThroughData: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/parking/configParkThrough/add',
        edit: '/parking/configParkThrough/edit',
        delete: '/parking/configParkThrough/delete',
        ParkArmList: '/parking/parkArmInfo/ParkArmList',
        ParkThroughData: '/parking/configParkThrough/ParkThroughData',
        CarTypeList: '/ConfigCarType/configCarType/carTypeList',
        ArmThroughData: '/parking/configParkThrough/ArmThroughData',
      },
      ArmOptions: [],
      DayOptions: [
        { value: '1', label: '星期一', isChecked: false, index: 0 },
        { value: '2', label: '星期二', isChecked: false, index: 1 },
        { value: '3', label: '星期三', isChecked: false, index: 2 },
        { value: '4', label: '星期四', isChecked: false, index: 3 },
        { value: '5', label: '星期五', isChecked: false, index: 4 },
        { value: '6', label: '星期六', isChecked: false, index: 5 },
        { value: '7', label: '星期日', isChecked: false, index: 6 },
      ],
      CarOptions: [],
      ArmConfig: [],
      ArmRadioSelected: '',
      DayRadioSelected: '',
      CarRadioSelected: '',
      TableColumns: [
        {
          title: '车道',
          dataIndex: 'ArmName',
          width: '10%',
          scopedSlots: { customRender: 'ArmName' },
        },
        {
          title: '受控车辆类型',
          dataIndex: 'carTypeId',
          width: '20%',
          scopedSlots: { customRender: 'carTypeId' },
        },
        {
          title: '禁止通行日',
          dataIndex: 'stopWeeklyDay',
          width: '20%',
          scopedSlots: { customRender: 'stopWeeklyDay' },
          customRender: function (t) {
            const Week = t.split(',')
            let Str = ''
            Week.forEach((day) => {
              switch (day) {
                case '1':
                  day = '星期一'
                  break
                case '2':
                  day = '星期二'
                  break
                case '3':
                  day = '星期三'
                  break
                case '4':
                  day = '星期四'
                  break
                case '5':
                  day = '星期五'
                  break
                case '6':
                  day = '星期六'
                  break
                case '7':
                  day = '星期日'
                  break
              }
              if (Str.length === 0) {
                Str = Str + day
              } else {
                Str = Str + ',' + day
              }
            })
            return Str
          },
        },
        {
          title: '禁止通行开始时间',
          dataIndex: 'stopStartTime',
          width: '20%',
          scopedSlots: { customRender: 'stopStartTime' },
        },
        {
          title: '禁止通行结束时间',
          dataIndex: 'stopEndTime',
          width: '20%',
          scopedSlots: { customRender: 'stopEndTime' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      parkCode: '',
      parkName: '',
      stopWeeklyDays: '',
      carTypeIds: '',
      ArmRadioSelectedId: '',
      stopStartTime: '',
      stopEndTime: '',
    }
  },
  props: {
    parkInfo: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {
    this.throughEdit(this.parkInfo)
  },
  watch: {
    parkInfo() {
      this.throughEdit(this.parkInfo)
    },
  },
  methods: {
    moment,
    throughEdit(record) {
      this.FormReset()
      const that = this
      this.confirmLoading = true
      this.visible = true
      this.parkCode = record.parkCode
      this.parkName = record.parkName
      this.$nextTick(async () => {
        //时间格式化
        this.form.setFieldsValue({ updateTime: this.model.updateTime ? moment(this.model.updateTime) : null })
        this.form.setFieldsValue({ parkCode: record.parkCode })
        this.form.setFieldsValue({ parkName: record.parkName })

        await that.loadData()
      })
    },
    ArmRadioChange(index) {
      this.FormReset()
      this.ArmOptions.forEach((item) => {
        item.isChecked = false
      })
      //再设置当前点击项选中
      this.ArmRadioSelected = this.ArmOptions[index].value
      this.ArmRadioSelectedId = this.ArmOptions[index].id
      this.form.setFieldsValue({ serialNo: this.ArmRadioSelected })
      // 设置值，以供传递
      this.ArmOptions[index].isChecked = true
      this.loadArmData(this.ArmOptions[index].value)
    },
    DayRadioChange(index) {
      if (this.DayOptions[index].isChecked === true) {
        this.DayOptions[index].isChecked = false
      } else {
        this.DayOptions[index].isChecked = true
      }
    },
    CarRadioChange(index) {
      if (this.CarOptions[index].isChecked === true) {
        this.CarOptions[index].isChecked = false
      } else {
        this.CarOptions[index].isChecked = true
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk(model) {
      const that = this
      that.stopWeeklyDays = ''
      that.carTypeIds = ''

      that.DayOptions.forEach((day) => {
        if (day.isChecked === true) {
          if (that.stopWeeklyDays.length === 0) {
            that.stopWeeklyDays = day.value
          } else {
            that.stopWeeklyDays = that.stopWeeklyDays + ',' + day.value
          }
        }
      })
      this.CarOptions.forEach((car) => {
        if (car.isChecked === true) {
          if (that.carTypeIds.length === 0) {
            that.carTypeIds = car.value
          } else {
            that.carTypeIds = that.carTypeIds + ',' + car.value
          }
        }
      })
      if (this.ArmRadioSelectedId.length === 0) {
        this.$message.warning('请选择一个车道')
        return
      }
      if (this.stopWeeklyDays.length === 0 && (this.stopStartTime === '' || this.stopEndTime === '')) {
        this.$message.warning('请至少选择一个禁止通行日期或者通行时间段！')
        return
      }
      if (this.carTypeIds.length === 0) {
        this.$message.warning('请至少选择一个禁止通行车辆')
        return
      }
      this.form.setFieldsValue({ carTypeId: that.carTypeIds })
      this.form.setFieldsValue({ stopWeeklyDay: that.stopWeeklyDays })
      this.form.setFieldsValue({ serialNo: that.ArmRadioSelected })
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化
          formData.updateTime = formData.updateTime ? formData.updateTime.format('YYYY-MM-DD HH:mm:ss') : null
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                if (model === true) {
                  that.$emit('ok')
                }
              } else {
                //that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loadArmData(that.form.getFieldValue('serialNo'))
              that.LoadThroughData()
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onSelectChange: function (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    async loadData() {
      let that = this
      this.ArmOptions = []
      this.CarOptions = []
      this.stopWeeklyDays = []
      this.carTypeIds = []
      if (!this.url.ParkArmList) {
        this.$message.error('请设置url.CarTypeList!')
        return
      }
      let params = {}
      params.parkCode = this.form.getFieldValue('parkCode')

      //获取车场车道信息
      await getAction(this.url.ParkArmList, params).then((res) => {
        if (res.success) {
          if (!that.form) {
            return
          }
          var arr = []
          var i = 0
          res.result.forEach((Arm) => {
            arr.push({
              index: i,
              isChecked: false,
              value: Arm.serialNo,
              id: Arm.id,
              label: Arm.armName,
            })
            i++
          })
          that.ArmOptions = arr
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
      //获取当前车场的车道通行配置
      params.method = 'Through'
      await getAction(this.url.CarTypeList, params).then((res) => {
        if (res.success) {
          var arr = []
          var i = 0
          res.result.forEach((Car) => {
            if (Car.carType !== '1'){
              arr.push({
                index: i,
                isChecked: false,
                value: Car.id,
                label: Car.carTypeName,
              })
              i++
            }
          })
          that.CarOptions = arr
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
      if (that.ArmOptions[0]) {
        that.ArmOptions[0].isChecked = true
        that.ArmRadioSelected = that.ArmOptions[0].value
        that.ArmRadioSelectedId = that.ArmOptions[0].id
        that.loadArmData(that.ArmOptions[0].value)
      }
      await that.LoadThroughData()
      that.confirmLoading = false
    },
    async loadArmData(ArmSerioNo) {
      this.confirmLoading = true
      let params = {}
      params.serialNo = ArmSerioNo
      const that = this
      if (!this.url.ArmThroughData) {
        this.$message.error('请设置url.ArmThroughData!')
        return
      }
      that.ArmConfig = await getAction(that.url.ArmThroughData, params).then((res) => {
        if (res.success) {
          return res.result
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
          return
        }
      })

      if (that.ArmConfig) {
        that.model.id = that.ArmConfig.id
        let ConfigCarTypeArray = that.ArmConfig.carTypeId.split(',')
        let ConfigStopWeeklyDay = that.ArmConfig.stopWeeklyDay.split(',')
        that.stopStartTime = moment(that.ArmConfig.stopStartTime, 'HH:mm:ss')
        that.stopEndTime = moment(that.ArmConfig.stopEndTime, 'HH:mm:ss')
        that.form.setFieldsValue({ stopStartTime: that.ArmConfig.stopStartTime })
        that.form.setFieldsValue({ stopEndTime: that.ArmConfig.stopEndTime })
        ConfigCarTypeArray.forEach((CarTypeId) => {
          that.CarOptions.forEach((car) => {
            if (car.value === CarTypeId) {
              car.isChecked = true
            }
          })
        })
        ConfigStopWeeklyDay.forEach((WeeklyDay) => {
          that.DayOptions.forEach((Day) => {
            if (Day.value === WeeklyDay) {
              Day.isChecked = true
            }
          })
        })
      } else {
        that.model.id = null
      }
      that.confirmLoading = false
    },
    onStartTimeChange(Format, time) {
      Format._i = time
      this.stopStartTime = Format
      if (this.stopStartTime !== '' && this.stopEndTime !== '') {
        this.form.setFieldsValue({ stopStartTime: this.stopStartTime._i })
      }
    },
    onEndTimeChange(Format, time) {
      Format._i = time
      this.stopEndTime = Format
      if (this.stopStartTime !== '' && this.stopEndTime !== '') {
        this.form.setFieldsValue({ stopEndTime: this.stopEndTime._i })
      }
    },
    FormReset() {
      this.DayOptions.forEach((item) => {
        item.isChecked = false
      })
      this.CarOptions.forEach((item) => {
        item.isChecked = false
      })
      this.stopStartTime = moment('00:00:00', 'HH:mm:ss')
      this.stopEndTime = moment('23:59:59', 'HH:mm:ss')
      this.form.resetFields(['carTypeId', 'stopEndTime', 'stopStartTime', 'stopWeeklyDay'])
    },
    Delete(id) {
      this.confirmLoading = true
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { invateuserdetailId: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.LoadThroughData()
        } else {
          that.$message.warning(res.message)
        }
      })
      if (this.model.id === id) {
        this.model.id = null
      }
    },
    async LoadThroughData() {
      this.confirmLoading = true
      if (!this.url.ParkThroughData) {
        this.$message.error('请设置url.ParkThroughData!')
        return
      }
      let that = this
      let params = {}
      params.parkCode = this.form.getFieldValue('parkCode')
      await getAction(this.url.ParkThroughData, params).then((res) => {
        if (res.success) {
          var arr = []
          res.result.forEach((Arm) => {
            arr.push({
              ArmName: Arm.serialNo,
              carTypeId: Arm.carTypeId,
              stopWeeklyDay: Arm.stopWeeklyDay,
              stopStartTime: Arm.stopStartTime,
              stopEndTime: Arm.stopEndTime,
              id: Arm.id,
            })
          })
          that.ThroughData = arr
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
      that.ThroughData.forEach((item) => {
        var CarTypeIdArr = item.carTypeId.split(',')
        var CarTypeNameArr = []
        that.ArmOptions.forEach((Arm) => {
          if (Arm.value === item.ArmName) {
            item.ArmName = Arm.label
          }
        })
        CarTypeIdArr.forEach((CarType) => {
          that.CarOptions.forEach((car) => {
            if (CarType === car.value) {
              CarTypeNameArr.push(car.label)
            }
          })
        })
        item.carTypeId = String(CarTypeNameArr).replaceAll(',', '/')
      })
      that.confirmLoading = false
    },
  },
}
</script>
<style scoped lang="less">
.ThroughConfigDiv {
  border-style: solid;
  border-width: 2px;
  border-color: #dee0e1;
  border-radius: 5px;
  overflow-y: auto;
}

.ThroughConfigDiv_Title {
  height: 35px;
  background-color: #f1f3f4;
  border-width: 0px;
  border-color: #dee0e1;
  border-bottom-width: 2px;
  border-style: solid;
  display: flex;
}

.ThroughConfigDiv_item {
  height: max-content;
  background-color: white;
}

/deep/ .ant-radio-wrapper {
  text-align: center;
  width: 100%;
  box-sizing: border-box;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  font-variant: tabular-nums;
  list-style: none;
  font-feature-settings: 'tnum';
  display: inline-block;
  white-space: nowrap;
  cursor: pointer;
}

/deep/ .ant-time-picker-input {
  margin-top: 0px;
  margin-bottom: 0px;
  width: 100%;
  height: 100%;
}

/deep/ .ant-time-picker {
  height: 100%;
  width: 100%;
  padding: 0px;
}

/deep/ .ant-table-column-title {
  font-size: 10px;
  margin: 5px;
}

/deep/ .ant-table-row-cell-break-word {
  padding-top: 5px;
  padding-bottom: 5px;
  padding-right: 0px;
  padding-left: 0px;

  font-size: 10px;
  text-align: center;
  font-weight: 500;
  color: black;
}

/deep/ .ant-table-header-column {
  width: 100%;
  text-align: center;
}

/deep/ .ant-table-tbody {
  height: 100%;
}

/deep/ tr.ant-table-row.ant-table-row-level-0 {
  height: 50px;
}

/deep/ .ant-table-tbody .ant-table-row td {
  padding-top: 5px;
  padding-bottom: 5px;
}
.RadioLabel {
  margin-top: 6px;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 0px;
}
</style>
